﻿using System.Security.Claims;

namespace tju.cme.BookStore2024.webapi.Models.Tools
{
    /// <summary>
    /// 从token中分析用户信息
    /// </summary>
    public class GetAuthorizedInfo
    {
        public static AuthorizedInfo? Get(ClaimsPrincipal user)
        {
            var sidClaim = user.Claims.FirstOrDefault(c => c.Type == "sid");
            var roleClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);

            if (sidClaim != null)
            {
                return new AuthorizedInfo()
                {
                    Id = Guid.Parse(sidClaim.Value),
                    Name = user.Identity!.Name ?? string.Empty,
                    Role = roleClaim != null ? roleClaim.Value : string.Empty
                };
            }
            else
                return null;
        }

        public static Guid GetId(ClaimsPrincipal user)
        {
            var sidClaim = user.Claims.FirstOrDefault(c => c.Type.EndsWith("sid"));
            if (sidClaim == null)
                throw new Exception("无登录信息");
            return Guid.Parse(sidClaim!.Value);
        }

        public static string GetRole(ClaimsPrincipal user)
        {
          
            // 从用户的Claims中获取Role
            var roleClaim = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role);

            // 如果没有找到Role的Claim，则返回null或者抛出异常
            if (roleClaim == null)
            {
                throw new Exception("未找到用户角色");
            }

            // 返回用户的Role
            return roleClaim.Value;
        }
    }


    /// <summary>
    /// 从token中分析出来的登录人员信息
    /// </summary>
    public class AuthorizedInfo
    {
        public Guid Id { get; set; }

        public string Name { get; set; } = null!;

        public string Role { get; set; } = null!;
    }
}
